package com.example.register_demo.home.LoginAndRegister

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.lifecycle.ViewModelProvider
import com.example.register_demo.home.HomeFragment

import com.example.register_demo.userDatabase.UserEntity
import com.example.remindme.HomePages.userDatabase.DatabaseViewModel
import com.example.remindme.R
import kotlin.concurrent.thread

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 * Use the [RegisterFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class RegisterFragment : Fragment() {
    // TODO: Rename and change types of parameters

    private lateinit  var register_btn: Button
    private lateinit var account_edit: EditText
    private lateinit var pass1_edit: EditText
    private lateinit  var pass2_edit: EditText
    private lateinit var nickname: EditText
    private lateinit var warning: TextView
    lateinit var passwordVM:RegisterModel
    private lateinit var if_remember:CheckBox
    private lateinit var dataViewModel : DatabaseViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        passwordVM= ViewModelProvider(this).get(RegisterModel::class.java)  // 添加livadata进来

    }
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

    }
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        return inflater.inflate(R.layout.fragment_register, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        val view=getView()
        if (view != null) {
            register_btn= view.findViewById(R.id.register)!!
            account_edit=view.findViewById(R.id.acount)!!
            pass1_edit=view.findViewById(R.id.password1)!!
            pass2_edit=view.findViewById(R.id.password2)!!
            nickname=view.findViewById(R.id.nickname)!!
            warning=view.findViewById(R.id.warning)!!
            if_remember=view.findViewById(R.id.register_remember)
        }
        initElement()  // 初始化控件
        initObserve()  // 添加监控，实时更新\
        initUserDatabase() // 初始化数据库
    }

    private fun initUserDatabase() {
        // 通过androidviewmodel 对数据库进行了进一步的封装
        dataViewModel=ViewModelProvider(this,
            ViewModelProvider.AndroidViewModelFactory.getInstance(activity?.application!!)).get(DatabaseViewModel::class.java)

        // userDAO=userDB.userDao()
    }

    private fun initObserve() {
        passwordVM.password2.observe(requireActivity(),{
            Log.d("vm","constrast")
            Constrast(it)

        })
        passwordVM.is_equals.observe(requireActivity(),{
            warning.text= if(it)""
            else
                "this pass word is not equal"
            register_btn.isEnabled=it    // 不相等的时候，不能进行注册
        })
        passwordVM.account.observe(requireActivity(),{
            //当账号内容发生变化时

            dataViewModel.getRealTimeUser(it).observe(requireActivity(),
                {
                    register_btn.isEnabled=it.isEmpty()   // 只有当此账户不存在（查询为空的时候），才能使用注册按钮
                    if(!it.isEmpty())
                       warning.text=",此账户已经使用过"
                    else
                        warning.text=""
                })
        })

    }

    private fun Constrast(str:String) {
        var pass1=pass1_edit.text.toString()
        passwordVM.is_equals.value= pass1.equals(str)
        Log.d("vm", "${pass1}:$str")
        Log.d("vm", "${passwordVM.is_equals.value}")
    }

    private fun initElement() {

        pass2_edit.addTextChangedListener(object: TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                Log.d("listener",s.toString())
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }
            override fun afterTextChanged(s: Editable?) {
                passwordVM.password2.value=s.toString()
            }
        })

        passwordVM.is_equals.value=true

        register_btn.setOnClickListener{
            // room 操作
            var remember=0
            if(if_remember.isChecked)
                remember=1
            val tempEntity= UserEntity(account_edit.text.toString(),
                pass1_edit.text.toString(),
                nickname.text.toString(),
                    remember
            )
            thread {
                dataViewModel.userDao.insertRegister(tempEntity)
            //   Toast.makeText(requireActivity(),"Register successfully!",Toast.LENGTH_SHORT).show()
            }

            val fragment= HomeFragment()
            requireActivity().supportFragmentManager.beginTransaction()
                    .add(R.id.fragmentcontainer,fragment,"register")
                    .addToBackStack(null)
                    .remove(this)
                    .commit()

        }

    }
}